﻿namespace ufida.u9.ait.openapi
{
	using System;
	using System.Collections.Generic;
	using System.Text;
    using ufida.u9.ait.openapi.utils;
    using UFIDA.U9.Base;
    using UFIDA.U9.CBO.HR.Department;
    using UFIDA.U9.ISV.DeptOperatorSV;
    using UFIDA.U9.ISV.DeptOperatorSV.Proxy;
    using UFSoft.UBF.AopFrame;	
	using UFSoft.UBF.Util.Context;

	/// <summary>
	/// DeptSave partial 
	/// </summary>	
	public partial class DeptSave 
	{	
		internal BaseStrategy Select()
		{
			return new DeptSaveImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class DeptSaveImpementStrategy : BaseStrategy
	{
		public DeptSaveImpementStrategy() { }

		public override object Do(object obj)
		{						
			DeptSave bpObj = (DeptSave)obj;

			try
			{
				if (bpObj.Data == null || bpObj.Data.Count == 0)
					throw new Exception("传入参数为空");
				//预处理
				PreSave(bpObj.Data);
				List<DepartmentData> retlist = new List<DepartmentData>();
				List<object> inputdtos = DTOUtils.DTOListPropCopy(bpObj.Data.ConvertAll(item => item as object)
					, typeof(CopyOfDepartmentDTOData));
				foreach (CopyOfDepartmentDTOData dto in inputdtos)
				{
					Department item = Department.Finder.Find($"Code='{dto.Code}' and Org={Context.LoginOrg.ID}");
					dto.Org = new UFIDA.U9.CBO.Pub.Controller.CommonArchiveDataDTOData
					{
						ID = Context.LoginOrg.ID,
						Code = Context.LoginOrg.Code,
					};

					if (item == null)
					{
						//新增逻辑
						BatchCreateDeptByDTOSVProxy proxy = new BatchCreateDeptByDTOSVProxy();
						proxy.Dept=new List<CopyOfDepartmentDTOData> { dto };
                        List<DepartmentData> ret = proxy.Do();
						if (ret.Count > 0)
							retlist.Add(ret[0]);
					}
					else
					{
						//修改逻辑
						BatchModifyDeptByDTOSVProxy proxy = new BatchModifyDeptByDTOSVProxy();
						proxy.Dept = new List<CopyOfDepartmentDTOData> { dto};
                        List<DepartmentData> ret = proxy.Do();
						if (ret.Count > 0)
							retlist.Add(ret[0]);
					}
				}
				return ResultUtils.success(bpObj, bpObj.Data, retlist);
			}
			catch (Exception ex)
			{
				return ResultUtils.error(bpObj, bpObj.Data, ex);
			}
		}

        private void PreSave(List<CopyOfCopyOfDepartmentDTOData> data)
        {
            foreach(var item in data)
			{
				if (item.Effective == null)
				{
					item.Effective = new UFIDA.U9.Base.PropertyTypes.EffectiveData()
					{
						EffectiveDate = DateTime.Now.Date,
						IsEffective = true,
                        //去掉时分秒
                        DisableDate = DateTime.MaxValue.Date,
					};
				}
				else
				{
                    //去掉时分秒
                    item.Effective.DisableDate = DateTime.MaxValue.Date;
                }
				
			}
        }
    }		
	#endregion
	
}